# Copyright 2009 http://www.yuntien.com
# Licensed under the Apache License, Version 2.0

from ytblog.controller.common import *
from ytblog.helper.cache import *

class BlogListController(BlogController):

  #render html to client
  def render(self, context, delta=False):
    if delta == False:
      file_name = 'index.html'
    else:
      file_name = 'div_blogs.html'
    
    path = os.path.join(os.path.dirname(__file__), ytblog.config.TEMPLATE_DIR + file_name)
    self.response.out.write(template.render(path, context)) 

  #get blog query object, with or without filters
  def get_blog_query(self, filters=None):
    blogs_query = Blog.all()
    
    if filters is not None:
      for filter in filters:
        filter(blogs_query)

    return blogs_query

  def get_common_filters(self):
    filters = []
    query = self.request.GET
    
    if query.has_key('tag'):
      filters.append(lambda blogs: blogs.filter('tags =', query['tag']))
    if query.has_key('datefrom'):
      filters.append(lambda blogs: blogs.filter('date >=', query['datefrom']))
    if query.has_key('dateto'):
      filters.append(lambda blogs: blogs.filter('date <=', query['dateto']))
      
    filters.append(lambda blogs: blogs.order('-date'))
    return filters
      
  def get_filters(self):
    filters = []
    if ytblog.config.USE_PROMOTION:
      filters.append(lambda blogs: blogs.filter('popular =', True))
    filters = filters + self.get_common_filters()
    return filters   

  def get_blogs(self):
    query = self.get_blog_query(filters = self.get_filters())
    return self.get_page_objects(query, ytblog.config.BLOG_NUM_PER_PAGE)
  
  def get_page(self):
    blogs, page = self.get_blogs() 
    
    context = {
      'blogs': [self.fill_blog_info(blog) for blog in blogs],
      'page': page,
      }
    self.add_common_context(context)
    self.render(context)
    
  @check_page_cache
  def get(self):
    self.get_page()
    
class BlogAllListController(BlogListController):

  def get_filters(self):
    return self.get_common_filters()  

class BlogMyListController(BlogListController):

  def get_filters(self):
    filters = self.get_common_filters()
    filters.append(lambda blogs: blogs.filter('author =', users.get_current_user()))
    return filters        

  def get(self):
    self.get_page()
